import 'dart:convert';
import 'dart:math';

import 'package:flutter/material.dart';
import 'mixin.dart' show WebViewContextStateMixin;
import 'package:webview_flutter/webview_flutter.dart';
import 'package:webview_flutter_wkwebview/webview_flutter_wkwebview.dart';

import 'webview_bridge_dispatcher.dart';
import 'webview_init_js.dart';
import 'empjsapi.dart';

///
///  flutter 官方提供的webview封装
///  提供jssdk注入
///
class WebViewPage extends StatefulWidget {
  final String? title;
  final String baseUrl;

  const WebViewPage({Key? key, this.title, required this.baseUrl}) : super(key: key);

  @override
  WebViewPageState createState() => WebViewPageState();
}

class WebViewPageState extends State<WebViewPage> with WebViewContextStateMixin<WebViewPage> {
  @override
  late String baseUrl = widget.baseUrl;
  late WebViewController _controller;
  late WebViewBridgeDispatcher webViewDispatcher = WebViewBridgeDispatcher.of(this);

  @override
  void initState() {


    WidgetsFlutterBinding.ensureInitialized();
    super.initState();
    late final PlatformWebViewControllerCreationParams params;
    if (WebViewPlatform.instance is WebKitWebViewPlatform) {
      params = WebKitWebViewControllerCreationParams(
        allowsInlineMediaPlayback: true,
      );
    } else {
      params = const PlatformWebViewControllerCreationParams();
    }

    _controller = WebViewController.fromPlatformCreationParams(params)
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setNavigationDelegate(
        NavigationDelegate(
            // onNavigationRequest: (request) {
            //   if (request.url.endsWith('/android')) {
            //     // 跳到原生页面
            //     return NavigationDecision.prevent;
            //   } else {
            //     // 继续原来的请求
            //     return NavigationDecision.navigate;
            //   }
            // },
            // NavigationRequest request
          onPageStarted: (_) {
            // _controller.runJavaScript(webViewInitJs);//runJavaScriptReturningResult
            _controller.runJavaScript(empjsapi);//runJavaScriptReturningResult
          },
            // onPageFinished: (url) async {
            //   print("页面加载完成：$url");
            // },
          onPageFinished: (url) async {
            // await Future.delayed(Duration(milliseconds: 50));
            // var message = await _controller.runJavaScriptReturningResult(
            //     'document.scrollingElement.scrollHeight');
            // setState(() {
            //   // height =double.parse(message.toString());
            // });
          },
          // onNavigationRequest: (NavigationRequest request) async {
          //   if (request.url.startsWith('https://www.example.com/api')) {
          //     // 构造新的响应内容
          //     String modifiedResponse = '{"message": "Modified response"}';
          //     // 使用 evaluateJavascript 方法执行 JavaScript 代码来加载新的响应内容
          //     _controller.evaluateJavascript(
          //       'document.open();'
          //           'document.write(\'$modifiedResponse\');'
          //           'document.close();',
          //     );
          //     // 返回 NavigationDecision.prevent 表示拦截请求
          //     return NavigationDecision.prevent;
          //   }
          //   // 允许加载其他 URL
          //   return NavigationDecision.navigate;
          // },
          // onUrlChange: (url) async {
          //   // 在 URL 变化时拦截并改写请求
          //   if (url.startsWith('https://www.example.com/api')) {
          //     // 构造新的响应内容
          //     String modifiedResponse = '{"message": "Modified response"}';
          //     // 使用 runJavaScript 方法执行 JavaScript 代码，替换原始响应
          //     _controller.runJavaScript(
          //       'document.open();'
          //           'document.write(\'$modifiedResponse\');'
          //           'document.close();',
          //     );
          //   }
          // },
        ),
      )
      // ..addJavaScriptChannel(
      //   'FlutterBridge',
      //   onMessageReceived: webViewDispatcher.onMessageReceived,
      // )
      ..addJavaScriptChannel("Flutter", onMessageReceived: (message) {
      print("Flutter received: ${message.message}");

      final jsonObject = json.decode(message.message);
      final token = jsonObject['token'];
    print('token=====${token}');
    final str = 'receiveAppMessage({\"data\":[{\"username\":\"yemh\",\"empId\":\"yemh\",\"imid\":\"yemh\",\"name\":\"叶明辉\",\"userId\":\"yemh\",\"avatar\":\"http:\\/\\/evo.hywhir.net:8808\\/upload\\/whrj\\/userIcon\\/202404\\/20240411\\/cbdf71ee21914222a2b0bed8568e0e63.jpg\"}],\"resultStatus\":0,\"type\":\"result.success\",\"token\":"${token}"})';
      print('str=====${str}');

      _controller.runJavaScriptReturningResult(str);
    })
      // ..addJavaScriptChannel('Report', onMessageReceived: (message) {
      //   setState(() {
      //     height = double.parse(message.message);
      //   });
      // })
    // 192.168.50.142
      ..loadRequest(Uri.parse('http://192.168.50.142:8082/empdoc/'));
      // ..loadFlutterAsset('lib/assets/index.html');
      
    webViewDispatcher.setController(_controller);
  }



  bool showAppbar = true;

  @override
  void setAppbar(bool show) {
    setState(() {
      showAppbar = show;
    });
  }

  @override
  void dispose() {
    super.dispose();
    webViewDispatcher.dispose();
  }

  void onTestCallJsFunction() {
    webViewDispatcher.jsClient.getJsInfo({'number': Random().nextInt(1000)}).then((value) {
      print("js返回的数据=======${value}");
    }).catchError((e){
      print("调用方法错误===$e");
    });

    // webViewDispatcher.functionHandler.getUserInfo(webViewDispatcher.functionHandler.clients, {}).then((value){
    //   print("js返回的数据=======${value}");
    // }).catchError((e){
    //   print("调用方法错误===$e");
    // });

    //以上写法等价于
    // webViewDispatcher.jsClient.callJsFunc('getJsInfo', {'status': '12312'}).then((value) {
    //   print("js返回的数据=======${value}");
    // });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: showAppbar
          ? AppBar(
              title: const Text('官方插件 webview_flutter'),
              actions: [
                TextButton(onPressed: onTestCallJsFunction, child: Text('调用js端')),
              ],
            )
          : null,
      body: WebViewWidget(
        controller: _controller,
      ),
    );
  }
}
